package com.aiguigu.admin.controller;

import com.aiguigu.admin.bean.Account;
import com.aiguigu.admin.bean.City;
import com.aiguigu.admin.bean.User;

import com.aiguigu.admin.service.AccountService;
import com.aiguigu.admin.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;

@Controller
public class IndexController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    AccountService accountService;

    @PostMapping("/city")
    @ResponseBody
    public City saveCity(City city){
        cityService.saveCity(city);
        return city;
    }
    @Autowired
    CityService cityService;
    @ResponseBody
    @GetMapping("city")
    public City getCityById(@RequestParam("id") Long id){
        return cityService.getById(id);
    }

    @ResponseBody
    @GetMapping("/acct")
    public Account getById(@RequestParam("id") Long id){
        Account account = accountService.getAcctById(id);

        return account;
    }

    @ResponseBody
    @GetMapping("/sql")
    public String testdatasource(){
        Long aLong = jdbcTemplate.queryForObject("select count(*) from account_tb1", Long.class);
        return aLong.toString();
    }
    //登陆页跳转
    @GetMapping(value = {"/","/login"})
    public String loginPage(){
        return "login";
    }

    @PostMapping("login")
    public String main(User user, HttpSession session, Model model){
        if (!StringUtils.isEmpty(user.getUsername()) && "123456".equals(user.getPassword())){
            //把登录成功的用户保存起来
            session.setAttribute("loginUser",user);
            //登陆成功重定向到html
            return "redirect:/main.html";

        }else {
            //相当于存进request
            model.addAttribute("msg","账号密码错误");
            //回到登陆页面
            return "login";
        }


    }
    //去main页面，防止表单重复提交
    @GetMapping("/main.html")
    public String mainPage(HttpSession session,Model model){
//        Object loginUser = session.getAttribute("loginUser");
//        if (loginUser!=null){
//            return "main";
//        }else {
//            model.addAttribute("msg","请重新登陆");
//            return "login";
//        }
        return "main";
    }
}
